package com.hup.minicontroller.server.hardware;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.lang.reflect.Method;

/**
 * Created by caigh on 2017/9/26.
 */

public class WifiUtil {
    private static final String TAG = WifiUtil.class.getSimpleName();

    private static WifiManager wifiMgr;

    public static void init(Context context) {
        wifiMgr = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }

    /**
     * 开启热点
     * 如果热点已经开启 则不改变原有的账号密码,直接返回
     */
    public static void startAP(String ssid, String pwd) {
        if (wifiMgr.isWifiEnabled()) {
            wifiMgr.setWifiEnabled(false);
        }

        if (!isAPEnabled()) {
            changeAPInner(ssid, pwd, true);
        }
    }

    public static void closeAp() {
        if (isAPEnabled()) {
            changeAPInner("ssid", "00012345678", false);
        }
    }


    /**
     * @return
     */
    @SuppressWarnings("ConstantConditions")
    public static boolean isAPEnabled() {
        try {
            //@SystemApi
            Method method = wifiMgr.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(wifiMgr);
        } catch (Exception e) {
            Log.e(TAG, "isAPEnabled: ", e);
            return false;
        }
    }

    private static void changeAPInner(String ssid, String pwd, boolean isOn) {
        try {
            //@SystemApi
            Method method = wifiMgr.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            WifiConfiguration netConfig = new WifiConfiguration();
            netConfig.SSID = ssid;
            netConfig.preSharedKey = pwd;
            netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            method.invoke(wifiMgr, netConfig, isOn);
        } catch (Exception e) {
            Log.e(TAG, "changeAPInner: ", e);
        }
    }

}
